package Engine.Model
{
	import Interface.Model.IKeyEventManager;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	
	import library.Function.Dict;

	public class KeyEventMannager implements IKeyEventManager
	{
		private var _stage:Stage;
		private var _isLestinUpEvent:Boolean;
		private var _isLestinDownEvent:Boolean;
		private var _keyUpDict:Dict;
		private var _keyDownDict:Dict;
		
		public function KeyEventMannager()
		{
			this._isLestinUpEvent = false;
			this._isLestinDownEvent = false;
			this._keyDownDict = new Dict(true);
			this._keyUpDict = new Dict(true);
		}
		
		public function setStage(stage:Stage):void
		{
			this._stage = stage;
		}
		
		public function regestKeyUpEvent(key:int,fun:Function):void
		{
			if(fun == null)
				return;
			this._keyUpDict.dictionary[key] = fun;
			if(!this._isLestinUpEvent)
			{
				this._stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
				this._isLestinUpEvent = true;
			}
		}
		
		public function destroyKeyUpEvent(key:int):void
		{
			this._keyUpDict.remove(key);
			if(this._keyUpDict.length == 0)
			{
				this._stage.removeEventListener(KeyboardEvent.KEY_UP,onKeyUp);
				this._isLestinUpEvent = false;
			}
		}
		
		public function regestKeyDownEvent(key:int,fun:Function):void
		{
			if(fun == null)
				return;
			this._keyDownDict.dictionary[key] = fun;
			if(!this._isLestinDownEvent)
			{
				this._stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				this._isLestinDownEvent = true;
			}
		}
		
		public function destroyKeyDownEvent(key:int):void
		{
			this._keyDownDict.remove(key);
			if(this._keyDownDict.length == 0)
			{
				this._stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				this._isLestinDownEvent = false;
			}
		}
		
		private function onKeyDown(e:KeyboardEvent):void
		{
			if(this._keyDownDict.has_key(e.keyCode))
				this._keyDownDict.dictionary[e.keyCode]();
		}
		
		private function onKeyUp(e:KeyboardEvent):void
		{
			if(this._keyUpDict.has_key(e.keyCode))
				this._keyUpDict.dictionary[e.keyCode]();
		}
		
	}
}